<template>
  <div class="contents">
    <el-row :gutter="10">
      <el-col :span="11">
        <div class="left">
        <el-card class="box-card" shadow="always">
        <div class="row-bg" v-if="isShow">
          <el-row>
          <el-col :span="20">
          <el-form :inline="true" :model="listQuery" size="small">
            <el-form-item >
              <el-input clearable @clear="clearMethod" size="mini" v-model="listQuery.name"
              placeholder="输入名称或描述搜索"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success"  size="mini" icon="el-icon-search" @click="onQuery()"
              >查询</el-button>
            <el-button type="warning" size="mini" icon="el-icon-refresh-left" @click="clearMethod"
              >重置</el-button>
          </el-form-item>
        </el-form>
        </el-col>
        </el-row>
      </div>
      <div class="second">
          <el-row type="flex" justify="space-between">
          <el-col :span="19">
                <el-button type="primary" size="mini" icon="el-icon-circle-plus" @click="addDict()" >新增</el-button>
                <el-button type="success" size="mini" icon="el-icon-edit" :disabled="isDisabled"
                          @click.native.prevent="editRows()" >编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="isDisabled"
                          @click.native.prevent="popDelete()" >批量删除</el-button>
                <el-button type="warning" size="mini" icon="el-icon-download">导出</el-button>
          </el-col>
          <!-- 按钮组 -->
          <el-col :span="5">
              <div class="but">
              <el-button-group>
              <el-button type="info" icon="el-icon-search" size="mini" @click.native.prevent="changeIsShow"></el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="openFullScreen"
                          v-loading.fullscreen.lock="fullscreenLoading"></el-button>
              <template>
                <el-popover placement="bottom" width="150px" text-align=center; trigger="click">
                  <el-checkbox v-model="checkedName" @change="IsShowName">名称</el-checkbox>
                  <el-checkbox v-model="checkedDescribe" @change="IsShowDescribe">描述</el-checkbox>
                  <el-button slot="reference" icon="el-icon-s-grid" size="mini"></el-button>
                </el-popover>
              </el-checkbox-group>
              </template>
              </el-button-group>
              </div></el-col>
          </el-row>
      </div>
    <el-table :data="list" style="width: 100%" stripe border ref="multipleTable"
              tooltip-effect="dark" @selection-change="handleSelectionChange"
              @cell-click="tableColum">
      <el-table-column type="selection" width="50" align="center">
      </el-table-column>
      <el-table-column prop="name" label="名称"  align="center" v-if="isShowName" v-model="dictName">
      </el-table-column>
      <el-table-column prop="description" label="描述" align="center" v-if="isShowDescribe">
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          </el-button>
          <el-button type="primary" icon="el-icon-edit" title="单编辑" circle
                      @click.native.prevent="EditRow(scope.row)">
          </el-button>
          <el-button type="danger" icon="el-icon-delete" title="删除" circle
                      @click.native.prevent="DelAction(scope.row)" >
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <!-- ====================主表格 分页===================== -->
      <el-col :span="20">
        <div>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :page-size="listQuery.pageSize"
            :page-sizes="[8, 15]"
            :pager-count="5"
            :current-page.sync="listQuery.pageNum"
            :total="total"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
        <!-- ======================主表格 弹框===============---------- -->
        <el-dialog :visible.sync="multiAddVisible" :title="addtitle" width="35%" customClass="dialogClass"
                    :showClose="false">
        <el-form label-width="100px" :model="dict" :rules="dictRules" ref="form">
              <el-form-item label="字典名称：" prop="name">
                <el-input size="small" v-model="dict.name"></el-input>
              </el-form-item>
              <el-form-item label="描述：" prop="description">
                <el-input size="small" v-model="dict.description"></el-input>
              </el-form-item>
        </el-form>
            <span slot="footer">
              <el-button round type="info" icon="el-icon-circle-close" @click="popupCancel()">取 消</el-button>
              <el-button round type="primary" icon="el-icon-circle-check" @click="onSubmit('form')">提 交</el-button>
            </span>
          </el-dialog>
        </el-card>
        </div>
      </el-col>

      <!-- ==========================子表格============组件==============子表格=============================== -->
      <el-col :span="13">
        <div class="right">
      <dict-detail ref="detilRef" :hintIsShow="hintIsShow" :tableIsShow="tableIsShow"></dict-detail>
        </div>
      </el-col>


    </el-row>
  </div>
</template>

<script>
import {
  fetchList, //主表查询
  getAllId,  //子表查询
  createDict, //主表添加
  deleteDictBatch, //主表批量删除GET
  deleteDict,  //主表单删
} from "@/api/dict";

import DictDetail from './dictDetail'

export default {

  components:{
    DictDetail
  },

  data() {
    return {
      fullscreenLoading: false,
      dictId:5,
      dictName:'',
      dictDescription:'',
      addtitle: "新增字典",
      uptitle: "新增字典详情",
      search: '',
      checkedName: true,
      checkedDescribe:true,
      checkedHandle:true,
      isDisabled: true, //是否禁用确定按钮
      multiAddVisible:false,
      AddVisible:false,
      isShow:true,
      isShowName:true,
      isShowDescribe:true,
      hintIsShow:true,
      tableIsShow:false,
      arr:[{}],
      dict:{
        dictId:null,
        name:null,
        description:null,
        createdBy:null,
      },
      detail:{
        detailId:null,
        dictId:null,
        label:null,
        value:null,
      },
      listQuery: {
        pageNum: 1,
        pageSize: 8
      },
      form: {
        name: ""
      },
      listQuery2: {
        dictId:null,
        pageNum: 1,
        pageSize: 6
      },
      delArrParam: {
        ids: null
      },
      total: null,
      totals: null,
      list: null,
      list2:null,
      rows: null,
      allid:'',
      sonid:'',
      // 验证规则
      dictRules: {
        name: [{ required: true, trigger: "blur", message: "请输入名称" }],
        description: [
          { required: true, trigger: "blur", message: "请输入描述" }
        ],
        label: [{ required: true, trigger: "blur", message: "请输入标签" }],
        value: [{ required: true, trigger: "blur", message: "请输入值" }],
      }
    };
  },
  created() {
    this.getList();
  },

  //全表关键词搜索
  // computed:{
  //     list:function(){
  //       var search=this.search;
  //       if(search){
  //         return  this.getList().filter(function(dataNews){
  //           return Object.keys(dataNews).some(function(key){
  //             return String(dataNews[key]).toLowerCase().indexOf(search) > -1
  //           })
  //         })
  //       }
  //       return this.getList()
  //     }
  //   },

  methods: {
    // Loading 整页加载
    openFullScreen() {
        this.fullscreenLoading = true;
        setTimeout(() => {
        this.fullscreenLoading = false;
        }, 900);
    },
    //显示隐藏
    changeIsShow:function(){
      this.isShow=!this.isShow;
    },
    IsShowName:function(){
      this.isShowName=!this.isShowName;
    },
    IsShowDescribe:function(){
      this.isShowDescribe=!this.isShowDescribe;
    },
    //取消选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 获取选中的数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length == 0) {
        this.isDisabled = true;
      }else{
        this.isDisabled = false;
      }
    },

     //主表弹框取消
    popupCancel(){
      this.multiAddVisible = false;
      this.getList();
    },

    //主表按钮新增
    addDict() {
      this.multiAddVisible=true;
      this.addtitle="新增字典";
      this.dict.dictId=null;
      this.dict.name=null;
      this.dict.description=null;
      this.getList();
    },

    //主表编辑修改
    EditRow(row) {
      this.multiAddVisible=true;  //显示弹框
      this.addtitle="修改字典";
      this.dict = row;         //row当前行数据，把当前行的数据赋值给 表单
      this.allid = row.id;     //把id存全局
    },


    //-----主表格提交修改++++++++
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
      if (valid) {
        if (!this.allid) {
          //添加
          console.log(this.allid);
          createDict(this.dict).then(response => {
            if (response.code == 200) {
              this.$message({
                message: "提交成功",
                type: "success",
                duration: 1000
              });
              this.multiAddVisible = false;
              this.$refs.form.resetFields(); //清空表格数据
              this.getList();
            } else {
              this.$message({
                message: response.msg,
                type: "error",
                duration: 1000
              });
            }
          });
        } else {  // 修改
            let id = this.allid
            let params = {
              name:this.dict.name,
              description:this.dict.description,
            }
            updateDict(id,params).then(response => {
                if (response.code == 200) {
                  this.$message({
                    message: "提交成功",
                    type: "success",
                    duration: 1000
                  });
                  this.multiAddVisible = false;
                  this.$refs.form.resetFields(); //清空表格数据
                  this.getList();
                } else {
                  this.$message({
                    message: response.msg,
                    type: "error",
                    duration: 1000
                  });
                }
              });
            }
        }else {
          this.$message.error("表单信息不能为空");
          this.multiAddVisible = true;
        }
      });
    },

    //主表单删除
    DelAction(row) {
      console.log("==================");
      this.$confirm("是否要删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteDict(row.dictId).then(response => {
          if (response.code == 200) {
            this.getList();
            this.$message({
              message: "删除成功",
              type: "success",
              duration: 1000
            });
            this.hintIsShow=true;
            this.tableIsShow=false;
          } else {
            this.$message({
              showClose: true,
              message: "警告，这条数据删除失败！",
              type: "warning",
              duration: 1000
            });
          }
        });
      });
    },

     //勾选框 编辑
    editRows(){
    
    },

    //主表GET批量删除
    popDelete() {
      this.rows = this.multipleSelection; // multipleSelection存储了勾选到的数据
      console.log("====33"+this.rows);
      let arr = [];
      let ids_str = "";
      this.rows.forEach(function(item) {
        arr.push(item.dictId);
        ids_str += item.dictId + ",";
      });
      ids_str = ids_str.substring(0, ids_str.length - 1);
      console.log(ids_str);
      this.delArrParam.ids = ids_str;
      this.$confirm("是否要删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteDictBatch(this.delArrParam).then(response => {
          console.log(response);
          if (response.code == 200) {
            this.getList();
            this.$message({
              message: "删除数据成功",
              type: "warning"
            });
          } else {
            this.$message.error("删除数据失败");
          }
        });
      });
    },


    // 主表分页
    getList() {
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data.records;
        this.arr = response.data.records;
        this.total = response.data.total;
        this.totalPage = response.data.pages;
        this.pageSize = response.data.size;
      });
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    //点主表格显示子表格详细   及 子表格分页
    tableColum(row){
      this.hintIsShow=false,
      this.tableIsShow=true,
      this.dictName=row.name;
      this.dictDescription=row.description
      this.dictId=row.dictId
      this.listQuery2.dictId=row.dictId
      this.getDictDetail()
       
      this.$refs.detilRef.initDetial(row.dictId,row.description,row.name);
    },
    getDictDetail(){
        getAllId(this.listQuery2).then(response => {
          this.list2 = response.data.records;
          this.totals= response.data.total;
          this.totalPage = response.data.pages;
          this.pageSize = response.data.size;
        })
    },
    handleSizeChanges(val) {
      this.listQuery2.pageNum = 1;
      this.listQuery2.pageSize = val;
      this.getDictDetail()
    },
    handleCurrentChanges(val) {
      this.listQuery2.pageNum = val;
      this.getDictDetail()
    },


    //条件查询
    onQuery() {
      this.getList();
    },

    //搜索清除数据
    clearMethod() {
      this.listQuery.description = null;
      this.listQuery.name = null;
    },

  }
};
</script>



<style>
.contents {
  width: 97%;
  margin: 1% 1.5% 0 1.5%;
}
.box-card {
  width: 100%;
}

.second{
    margin-bottom: 3%;
}

.but{
    text-align: right;
}
.dialogClass{
  border-radius: 20px;
}

.hint{
  border: 1px solid whitesmoke;
  padding-left: 20px;
  line-height: 100px;
  border-radius: 4px;
  height: 100px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

</style>
